﻿using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyModel;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.Loader;
using System.Text;
using System.Linq;
using Framework.Domain.DomainObject;
using Framework.Domain.DomainObject.Bo;
using Framework.Domain.Interface.DomainObject.UnitOfWork;

namespace Framework.Domain.UnitOfWork
{
    public class AppUnitOfWork : DbContext, IAppUnitOfWork
    {
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            //注入Sql链接字符串
            optionsBuilder.UseSqlServer(@"Database=DDD;User ID=sa;Password=111111;Server=.;");
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            Type type = null;
            try
            {
                List<CompilationLibrary> compilationLibrary = DependencyContext
                    .Default
                    .CompileLibraries
                    .Where(x => !x.Serviceable && x.Type != "package").ToList();
                foreach (var _compilation in compilationLibrary)
                {
                    AssemblyLoadContext.Default
                    .LoadFromAssemblyName(new AssemblyName(_compilation.Name))
                    .GetTypes()
                    .Where(x => x.GetTypeInfo().BaseType != null && x.BaseType == (typeof(BaseBoEntity)))
                    .ToList().ForEach(t =>
                    {
                        type = t;
                        modelBuilder.Model.AddEntityType(t);
                    });
                }
                base.OnModelCreating(modelBuilder);
            }
            catch (Exception ex)
            {

            }
        }



        public DbSet<TEntity> CreateSet<TEntity>()
            where TEntity : class
        {
            return base.Set<TEntity>();
        }

        public new int SaveChanges()
        {
            return base.SaveChanges();
        }

        public void AttachRemove<TEntity>(TEntity item) where TEntity : class
        {
            base.Entry<TEntity>(item).State = EntityState.Deleted;
        }



    }
}
